<template>
    <div>
        <hyl-search :formType="searchType" :formColumns="searchColumns" :formColumnsRule="searchColumnsRule" :customColumnsData="customSearchColumnsData" v-on:getFormData="getSearchFormData"></hyl-search>
        <hyl-table :tableData="tableData" :columns="columns" :specialColumns="specialColumns" v-on:tableSelection="tableSelection">
            <template slot="buttons">
                <el-button type="text" icon="el-icon-edit" @click="handleClick({},'edit')">编辑</el-button>
                <el-button type="text" icon="el-icon-circle-plus-outline" @click="handleClick({},'add')">添加</el-button>
                <el-button type="text" icon="el-icon-delete" @click="handleClick({},'delete')">删除</el-button>
                <el-button type="text" icon="el-icon-setting" @click="handleClick({},'grantPermission')">授权</el-button>
            </template>
          <!-- 定制表格单元格所显示内容 -->
          <div slot="createTime" slot-scope="scope">{{scope.$row.createTime | dateString}}</div>
          <div slot="updateTime" slot-scope="scope">{{scope.$row.updateTime | dateString}}</div>
        </hyl-table>
        <hyl-pagination :total="total" v-on:fetch="fetch" :page-sizes="[5,10,15]"/>
        <!-- 增加,删除 对话框  start -->
        <el-dialog title="添加"  :visible="addDialogVisible" width="40%" :show-close="false">
            <hyl-form :formColumns="addColumns" :formColumnsRule="addColumnsRule" :customColumnsData="customAddColumnsData" v-on:getFormData="getAddFormData" v-on:handleCancel="handleCancel"></hyl-form>
        </el-dialog>
        <el-dialog title="编辑" :visible.sync="editDialogVisible" width="40%">
            <hyl-form :formType="editType" :editData="editData" :formColumns="editColumns" :formColumnsRule="editColumnsRule" :customColumnsData="customEditColumnsData" v-on:getFormData="getEditFormData" v-on:handleCancel="handleCancel"></hyl-form>
        </el-dialog>
        <el-dialog title="角色授权" :visible.sync="grantPermissionDialogVisible" width="40%">
          <el-button type="text" icon="el-icon-setting" @click="handleGrantClick({},'grantPermission')">授权</el-button>
          <el-tree :data="grantPermissionData"
                   ref="tree"
                   show-checkbox
                   node-key="id"
                   :expand-on-click-node="false"></el-tree>
        </el-dialog>
        <!-- 增加,删除 对话框  end -->
    </div>
</template>

<script>
import hylTable from '@/components/table'
import hylPagination from '@/components/pagination'
import hylForm from '@/components/form'
import hylSearch from '@/components/search'
import {fetch, del, post, put} from '@/utils/http'
import {mapGetters} from 'vuex'
export default {
  name: 'index',
  components: {
    hylTable,
    hylPagination,
    hylForm,
    hylSearch
  },
  data () {
    return {
      tableData: [],
      total: 0,
      page: 1,
      limit: 5,
      specialColumns: [{
        type: 'selection',
        width: '55'
      }, {
        type: 'index',
        indexMethod: this.indexMethod
      }],
      columns: [
        {'prop': 'code', 'label': 'code'},
        {'prop': 'name', 'label': '名称'},
        {'prop': 'createTime', 'label': '创建时间', width: 155},
        {'prop': 'updateTime', 'label': '修改时间', width: 155}],
      applicationName: '',
      controller: '',
      customAddColumnsData: {},
      addColumns: [
        {'prop': 'code', 'label': 'code', dataType: 'varchar'},
        {'prop': 'name', 'label': '名称', dataType: 'varchar'}
      ],
      addColumnsRule: {
        code: [
          {required: true, message: '请输入角色code', trigger: 'blur'}, /// 这个是element自带配置的
          {validator: this.validateCode, trigger: 'blur'} /// 自定义校验规则
        ],
        name: [
          {required: true, message: '请输入角色名称', trigger: 'blur'}, /// 这个是element自带配置的
          {validator: this.validateName, trigger: 'blur'} /// 自定义校验规则
        ]
      },
      addData: {},
      customEditColumnsData: {},
      editColumns: [
        {'prop': 'code', 'label': 'code', dataType: 'varchar'},
        {'prop': 'name', 'label': '名称', dataType: 'varchar'}
      ],
      editColumnsRule: {
        code: [
          {required: true, message: '请输入角色code', trigger: 'blur'}, /// 这个是element自带配置的
          {validator: this.validateCode, trigger: 'blur'} /// 自定义校验规则
        ],
        name: [
          {required: true, message: '请输入角色名称', trigger: 'blur'}, /// 这个是element自带配置的
          {validator: this.validateName, trigger: 'blur'} /// 自定义校验规则
        ]
      },
      editType: 'edit',
      editData: {},
      customSearchColumnsData: {},
      searchColumns: [
        {'prop': 'code', 'label': 'code', dataType: 'varchar'},
        {'prop': 'name', 'label': '名称', dataType: 'varchar'}
      ],
      cacheSearchData: {},
      searchColumnsRule: {},
      searchType: 'search',
      multipleSelection: [],
      editDialogVisible: false,
      addDialogVisible: false,
      grantPermissionDialogVisible: false,
      grantPermissionType: 'grantType',
      grantData: {},
      grantPermissionData: [],
      checkPermissionData: []
    }
  },
  mounted: function () {
    this.getColumns()
    this.fetch()
  },
  computed: {
    ...mapGetters(['token'])
  },
  methods: {
    handleGrantClick () {
      /// 处理角色授权
      /// 只选择子节点
      let checkedNodes = this.$refs.tree.getCheckedNodes(true)
      let nodes = []
      checkedNodes.forEach((item) => {
        nodes.push(item.id)
      })
      this.grantData.permissionIds = nodes.join(',')
      console.log(this.grantData)
      post(this.applicationName + '/' + this.controller + '/grantPermission', this.grantData).then((res) => {
        if (res.status === 200) {
          this.$message.success(res.message)
          this.grantPermissionDialogVisible = false
        } else {
          this.$message.error('失败:' + res.message)
        }
      })
    },
    handleClick (row = {}, type = '') {
      switch (type) {
        case 'add':
          // 显示添加数据对话框
          this.addDialogVisible = true
          // 如查要对数据进行处理,在此进行,如:datetime类型
          /// 数据处理完后,赋值操作
          this.addData = row
          // alert('add')
          break
        case 'delete':
          // 一行或多行删除操作
          if (this.multipleSelection.length > 0) {
            // 此处生成写法是默认数据库表中字段id为唯一key值,name这一行记录名称(方便知道删除的是神马!))
            let ids = ''
            let names = ''
            this.multipleSelection.forEach((selection) => {
              ids = ids + selection.id + ','
              names = names + selection.name + ','
            })
            this.$confirm(names + '确定要删除, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.delete(this.applicationName + '/' + this.controller + '/deleteBatch', {params: {ids: ids.slice(0, ids.length - 1)}})
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '取消操作!'
              })
            })
          } else {
            /// 不符合条件
            this.$confirm('此操作需要至少选中一行, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '取消操作!'
              })
            })
          }
          // alert('删除')
          break
        case 'edit':
          /// 判断是否选中一行,其它情况都不符合要求
          if (this.multipleSelection.length === 1) {
            this.editData = this.multipleSelection[0]
            /// 显示编辑对话框
            this.editDialogVisible = true
          } else {
            this.$confirm('此操作只能选中一行, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '取消操作!'
              })
            })
          }
          break
        case 'grantPermission':
          /// 判断是否选中一行,其它情况都不符合要求
          if (this.multipleSelection.length === 1) {
            this.editData = this.multipleSelection[0]
            this.grantData.roleId = this.editData.id
            /// 显示编辑对话框
            this.grantPermissionDialogVisible = true
            fetch(this.applicationName + '/' + this.controller + '/getAllPermissionByService').then((res) => {
              if (res.status === 200) {
                this.grantPermissionData = res.data
              } else {
                this.$message.error('错误:' + res.message)
              }
            })
            fetch(this.applicationName + '/' + this.controller + '/getPermissionByRoleId', {roleId: this.editData.id}).then((res) => {
              if (res.status === 200) {
                let data = []
                res.data.forEach((item) => {
                  data.push(item.id)
                })
                console.log(this.$refs.tree)
                console.log(data)
                this.$refs.tree.setCheckedKeys(data, true)
              } else {
                this.$message.error('错误:' + res.message)
              }
            })
          } else {
            this.$confirm('此操作只能选中一行, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '取消操作!'
              })
            })
          }
          // alert('edit')
          break
        default:
          alert('其它操作')
      }
    },
    handleCancel (type = '') {
      switch (type) {
        case 'add':
          this.addDialogVisible = false
          break
        case 'edit':
          this.editDialogVisible = false
          break
        default:
          alert('此对话框类型:+ type +不存,请查看代码')
          break
      }
    },
    indexMethod (index) {
      return index + 1 + (this.page - 1) * this.limit
    },
    tableSelection (val) {
      this.multipleSelection = val
    },
    fetch (page = {
      page: 1,
      limit: this.limit
    }) {
      Object.assign(page, this.cacheSearchData)
      fetch(this.applicationName + '/' + this.controller + '/page', page).then((res) => {
        if (res.status === 200) {
          this.tableData = res.data.rows
          this.total = res.data.total
          this.page = page.page
          this.limit = page.limit
        } else {
          this.$message.error(res.message)
        }
      })
    },
    delete (url, params) {
      del(url, params).then((res) => {
        this.$message.success('删除成功!')
        /// 刷新页面
        this.fetch()
      })
    },
    getColumns () {
      // var temp = [{'columnName': 'id', 'dataType': 'int'}, {'columnName': 'code', 'dataType': 'varchar'}, {'columnName': 'name', 'dataType': 'varchar'}, {'columnName': 'createTime', 'dataType': 'datetime'}, {'columnName': 'updateTime', 'dataType': 'datetime'}]
      this.applicationName = 'upms'
      this.controller = 'role'
      // temp.forEach(item => {
      //   var obj = {}
      //   obj.prop = item.columnName
      //   obj.label = item.columnName
      //   this.columns.push(obj)
      // })
      // console.log(JSON.stringify(this.columns))
    },
    getSearchFormData (formData = {}, type, refs) {
      console.log(formData)
      console.log(type)
      /// 缓存模糊查询条件
      this.cacheSearchData = formData
      /// 若formData数据为空,那么直接返回
      if (JSON.stringify(formData) === '{}') {
        return
      }
      /// searchForm做整体校验,通过提交
      refs['searchForm'].validate((valid) => {
        if (valid) {
          /// 提交
          let page = {
            limit: this.limit,
            page: this.page
          }
          /// 将formData对象赋给page对象
          Object.assign(page, formData)
          /// 模糊查询提交
          this.fetch(page)
        }
      })
    },
    getAddFormData (formData = {}, type, refs) {
      console.log(formData)
      console.log(type)
      /// 若formData数据为空,那么直接返回
      if (JSON.stringify(formData) === '{}') {
        return
      }
      /// addForm做整体校验,通过提交
      refs['addForm'].validate((valid) => {
        if (valid) {
          /// 提交
          post(this.applicationName + '/' + this.controller + '/add', formData).then((res) => {
            if (res.status === 200) {
              this.$message.success('添加成功!')
              this.addDialogVisible = false
              refs['addForm'].resetFields()
              this.fetch()
            } else {
              this.$message.info(res.message)
            }
          })
        }
      })
    },
    getEditFormData (formData = {}, type, refs) {
      console.log(formData)
      console.log(type)
      /// 若formData数据为空,那么直接返回
      if (JSON.stringify(formData) === '{}') {
        return
      }
      /// editForm提交
      refs['editForm'].validate((valid) => {
        if (valid) {
          put(this.applicationName + '/' + this.controller + '/update', formData).then((res) => {
            if (res.status === 200) {
              const h = this.$createElement
              this.$message({
                message: h('p', null, [
                  h('i', { style: 'color: teal' }, '更新成功!')
                ])
              })
              this.editDialogVisible = false
              this.fetch()
            } else {
              this.$message.info(res.message)
            }
          })
        }
      })
    },
    // 下面都是检验方法
    validateCode (rule, value, callback) {
      // 只能存在中文与字母
      let pattern = /^[a-z:_]{6,32}$/
      if (pattern.test(value)) {
        callback()
      } else {
        callback(new Error('请输入[6-32]位小写字母:_!'))
      }
    },
    validateName (rule, value, callback) {
      // 只能存在中文与字母
      let pattern = /^[\u4e00-\u9fa5A-Za-z]{4,36}$/
      if (pattern.test(value)) {
        callback()
      } else {
        callback(new Error('请输入[4-36]位数字字母!'))
      }
    }
  }
}
</script>

<style scoped>

</style>
